package com.ruicar.afs.cloud.channel.online.controller;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.admin.api.dto.UserSimpleInfoDto;
import com.ruicar.afs.cloud.admin.api.feign.AfsUserFeign;
import com.ruicar.afs.cloud.channel.cardealer.common.Constants;
import com.ruicar.afs.cloud.channel.common.until.ChannelRoleEnum;
import com.ruicar.afs.cloud.channel.online.condition.ChannelOnlineCondition;
import com.ruicar.afs.cloud.channel.online.entity.*;
import com.ruicar.afs.cloud.channel.online.service.*;
import com.ruicar.afs.cloud.channel.online.vo.ChannelOnlineInterFaceVo;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.log.annotation.SysLog;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.MessageParamEnum;
import com.ruicar.afs.cloud.message.sendmessage.dto.MessageDataDto;
import com.ruicar.afs.cloud.message.sendmessage.dto.SendMessageDto;
import com.ruicar.afs.cloud.message.sendmessage.dto.SendResultInfoDto;
import com.ruicar.afs.cloud.message.sendmessage.service.MessageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;

import static com.ruicar.afs.cloud.channel.online.untils.ChannelOnlineConstants.QUALITY_LEVEL_FIVE;

/**
 * @ClassName:ChannelExternalInterfaceController
 * @Description: 渠道外部接口-controller
 * @Author:mingzhi.li
 * @Date:2020/6/6 19:06
 * @Version: V1.0
 **/
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/channelInterFace")
@Api(value = "channelInterFace", description = "渠道外部接口")
public class ChannelExternalInterfaceController {

    /**
     * 基本信息
     */
    private final ChannelOnlineService channelOnlineService;

    /**
     * 收款账号
     */
    private final ChannelAccountInfoService channelAccountInfoService;

    /**
     * 风控数据
     */
    private final ChannelRiskInfoService channelRiskInfoService;

    /**
     * 保证金
     */
    private final ChannelQuotaInfoService channelQuotaInfoService;

    /**
     * 授权区域
     */
    private final ChannelAuthorizeRegionService channelAuthorizeRegionService;

    /**
     * 授权车型
     */
    private final ChannelAuthorizeVehicleTempService channelAuthorizeVehicleTempService;

    private final AfsUserFeign afsUserFeign;
    private final MessageService messageService;

    /**
     * 获取合作商/直营车商信息
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "/channelInfoForUserName")
    @ApiOperation("获取合作商/直营车商信息")
    public IResponse<ChannelOnlineInterFaceVo> getAffiliatedUnit(@RequestBody ChannelOnlineCondition condition) {

        ChannelBaseInfoTemp temp = channelOnlineService.getOne(Wrappers.<ChannelBaseInfoTemp>query().lambda()
                .eq(ChannelBaseInfoTemp::getId, condition.getChannelId()));

        ChannelOnlineInterFaceVo vo = new ChannelOnlineInterFaceVo();
        if (temp != null) {
            //返回整个渠道信息
            vo.setChannelBaseInfo(temp);

            //查询风控信息
            List<ChannelRiskInfoTemp> channelRiskInfoTempList = channelRiskInfoService.list(Wrappers.<ChannelRiskInfoTemp>query().lambda().eq(ChannelRiskInfoTemp::getChannelId, temp.getId().toString()));
            if (channelRiskInfoTempList != null && channelRiskInfoTempList.size() > 0) {
                //返回风控数据
                vo.setRisk(channelRiskInfoTempList);
            }
            //查询渠道保证金信息
            List<ChannelQuotaInfoTemp> channelQuotaInfoTempList = channelQuotaInfoService.list(Wrappers.<ChannelQuotaInfoTemp>query().lambda().eq(ChannelQuotaInfoTemp::getChannelId, temp.getId().toString()));
            if (channelQuotaInfoTempList != null && channelQuotaInfoTempList.size() > 0) {
                //返回渠道保证金信息
                vo.setQuota(channelQuotaInfoTempList);
            }

            //查询渠道授权区域信息
            List<ChannelAuthorizeRegionTemp> regionTempList = channelAuthorizeRegionService.list(Wrappers.<ChannelAuthorizeRegionTemp>query().lambda().eq(ChannelAuthorizeRegionTemp::getChannelId, temp.getId().toString()));
            if (regionTempList != null && regionTempList.size() > 0) {
                //返回授权区域信息
                vo.setRegion(regionTempList);
            }

            List<ChannelReceivablesAccountTemp> accountTempList = channelAccountInfoService.list(Wrappers.<ChannelReceivablesAccountTemp>query().lambda().eq(ChannelReceivablesAccountTemp::getChannelId, temp.getId().toString()));
            if (accountTempList != null && accountTempList.size() > 0) {
                //返回收款账号信息
                vo.setAcount(accountTempList);
            }

            //查询授权车型
            List<ChannelAuthorizeVehicleTemp> vehicleTempList = channelAuthorizeVehicleTempService.list(Wrappers.<ChannelAuthorizeVehicleTemp>query().lambda().eq(ChannelAuthorizeVehicleTemp::getChannelId, temp.getId().toString()));
            if (vehicleTempList != null && vehicleTempList.size() > 0) {
                //返回授权车型
                vo.setVehicle(vehicleTempList);
            }
        }
        return IResponse.success(vo);
    }

    @PostMapping(value = "/limitInfoReceive")
    @ApiOperation(value = "接收临时额度数据")
    @SysLog("接收临时额度数据")
    @Transactional(rollbackFor = Exception.class)
    public IResponse limitInfoReceive(@RequestBody List<ChannelQuotaInfoTemp> quotaInfoList) {

        if (quotaInfoList != null && quotaInfoList.size() > 0) {
            for (int i = 0; i < quotaInfoList.size(); i++) {
                ChannelQuotaInfoTemp temp = quotaInfoList.get(i);
                //根据渠道id、保证金类型、业务类型定位数据库具体某一步进行更新
                List<ChannelQuotaInfoTemp> list = channelQuotaInfoService.list(Wrappers.<ChannelQuotaInfoTemp>query().lambda()
                        .eq(ChannelQuotaInfoTemp::getChannelId, temp.getChannelId())
                        .eq(ChannelQuotaInfoTemp::getQuotaType, temp.getQuotaType())
                        .eq(ChannelQuotaInfoTemp::getBusinessType, temp.getBusinessType()));
                if (list != null && list.size() > 0) {
                    ChannelQuotaInfoTemp channelQuotaInfoTemp = list.get(0);
                    //获取剩余额度
                    BigDecimal surplusQuota = temp.getSurplusQuota() == null ? BigDecimal.ZERO : temp.getSurplusQuota();
                    //获取临时额度
                    BigDecimal tempQuota = temp.getTempQuota() == null ? BigDecimal.ZERO : temp.getTempQuota();
                    //剩余额度=剩余额度-临时额度
                    channelQuotaInfoTemp.setSurplusQuota(surplusQuota.subtract(tempQuota));
                    //临时额度清零
                    channelQuotaInfoTemp.setTempQuota(BigDecimal.ZERO);
                    channelQuotaInfoService.updateById(channelQuotaInfoTemp);
                }
            }
        }
        return IResponse.success("操作成功");
    }

    @PostMapping(value = "/qualityLevelUpdate")
    @ApiOperation(value = "接收优质等级数据")
    @SysLog("接收优质等级数据")
    @Transactional(rollbackFor = Exception.class)
    public IResponse qualityLevelUpdate(@RequestBody List<ChannelRiskInfoTemp> riskInfoList) {
        if (riskInfoList != null && riskInfoList.size() > 0) {
            for (int i = 0; i < riskInfoList.size(); i++) {
                ChannelRiskInfoTemp temp = riskInfoList.get(i);
                //根据渠道id、业务类型定位数据库具体某一步进行更新
                List<ChannelRiskInfoTemp> list = channelRiskInfoService.list(Wrappers.<ChannelRiskInfoTemp>query().lambda()
                        .eq(ChannelRiskInfoTemp::getChannelId, temp.getChannelId())
                        .eq(ChannelRiskInfoTemp::getBusinessType, temp.getBusinessType()));
                if (list != null && list.size() > 0) {
                    ChannelRiskInfoTemp channelRiskInfoTemp = list.get(0);
                    channelRiskInfoTemp.setQualityGrade(QUALITY_LEVEL_FIVE);
                    channelRiskInfoService.updateById(channelRiskInfoTemp);
                }
            }
        }
        return IResponse.success("操作成功");
    }
    @PostMapping(value = "/sendMsgToUpdatePool")
    @ApiOperation(value = "发送修改收款账号信息")
    public IResponse sendMsgToUpdatePool(@RequestParam("channelId")Long channelId, @RequestParam("content") String content) {
        ChannelBaseInfoTemp b =channelOnlineService.getById(channelId);
        if (ObjectUtil.isNotNull(b)){
            List<UserSimpleInfoDto> userList = new ArrayList<>();
            if(Constants.DIRECT.equals(b.getChannelBelong())){
                IResponse<List<UserSimpleInfoDto>> newCarUsers= afsUserFeign.getSimpleUserListByRoleCode(ChannelRoleEnum.ROLE_OWN_NEW_MANAGE_CHANNEL_DEVELOP.name());
                if (CommonConstants.SUCCESS.equals(newCarUsers.getCode())){
                    userList.addAll(newCarUsers.getData());
                }
                IResponse<List<UserSimpleInfoDto>> oldCarUsers= afsUserFeign.getSimpleUserListByRoleCode(ChannelRoleEnum.ROLE_OWN_OLD_MANAGE_CHANNEL_DEVELOP.name());
                if (CommonConstants.SUCCESS.equals(oldCarUsers.getCode())){
                    userList.addAll(oldCarUsers.getData());
                }
            }else{
                IResponse<List<UserSimpleInfoDto>> newCarUsers= afsUserFeign.getSimpleUserListByRoleCode(ChannelRoleEnum.ROLE_OTHER_NEW_MANAGE_CHANNEL_DEVELOP.name());
                if (CommonConstants.SUCCESS.equals(newCarUsers.getCode())){
                    userList.addAll(newCarUsers.getData());
                }
                IResponse<List<UserSimpleInfoDto>> oldCarUsers= afsUserFeign.getSimpleUserListByRoleCode(ChannelRoleEnum.ROLE_OTHER_OLD_MANAGE_CHANNEL_DEVELOP.name());
                if (CommonConstants.SUCCESS.equals(oldCarUsers.getCode())){
                    userList.addAll(oldCarUsers.getData());
                }
            }
            if (CollectionUtil.isNotEmpty(userList)){
                List<String> phoneList = userList.stream().map(UserSimpleInfoDto::getPhone).collect(Collectors.toList());
                List<MessageDataDto>  messageDataDto = new ArrayList<>();
                /**  短信发送 by ZC.GUO  **/
                if (CollectionUtil.isNotEmpty(phoneList)){
                    for (String phone : phoneList){
                        MessageDataDto dataDto = new MessageDataDto();
                        dataDto.setDeptId(MessageParamEnum.DEPTID.getCode());
                        dataDto.setOrigin(MessageParamEnum.ORIGIN.getCode());
                        dataDto.setPhone(phone);
                        /**  防重复-不防重复，有多少发多少 by ZC.GUO  **/
                        dataDto.setSummaryId(phone + String.valueOf(Calendar.getInstance().getTime().getTime())+ UUID.randomUUID().toString());
                        dataDto.setSmsContent(content);
                        dataDto.setTemplateId("W401");
                        dataDto.setPriority("1");
                        messageDataDto.add(dataDto);
                    }
                    SendMessageDto messageDto= new SendMessageDto();
                    messageDto.setChannel("1");
                    messageDto.setCode(MessageParamEnum.CODE.getCode());
                    messageDto.setTimestamp(System.currentTimeMillis()/1000+"");
                    messageDto.setUid(MessageParamEnum.UID.getCode());
                    messageDto.setMessageDataDto(messageDataDto);
                    SendResultInfoDto sendResultInfoDto = messageService.sendMessageData(messageDto);
                    if ("false".equals(sendResultInfoDto.getResult())) {
                        return IResponse.fail("发送失败，短信平台连接失败");
                    }
                    return IResponse.success("发送成功");
                }else{
                    return IResponse.fail("发送失败，渠道管理员为登记手机号码");
                }
            }else{
                return IResponse.fail("发送失败，无渠道管理员");
            }
        }else{
            return IResponse.fail("发送失败，渠道不存在");
        }
    }
}
